<template>
  <div class="main-content">
    <a-form :model="state.tableParams">
      <a-spin :spinning="state.todoCardSpinning">
        <a-row :gutter="8" type="flex">
          <a-col :span="24" v-if="false && state.checkedList.length === 0">
            <a-card title="待办统计" style="width: 100%">
              <template #extra>
                <span
                  @click="onTodoCardTabChange('personal', 'todoKey')"
                  :style="{
                    color: state.todoKey === 'personal' ? '#52acff' : ''
                  }"
                  >个人</span
                >
                <span v-if="state.isAdmin"> / </span>
                <span
                  @click="onTodoCardTabChange('department', 'todoKey')"
                  :style="{
                    color: state.todoKey === 'department' ? '#52acff' : ''
                  }"
                  v-if="state.isAdmin"
                  >部门</span
                >
              </template>

              <a-row type="flex" :gutter="8">
                <a-col :span="8">
                  <div class="card-list">
                    <div class="card-list-item">
                      <div>当前待处理待办共计</div>
                      <div class="card-list-item-desc">
                        <span class="card-list-item-value">{{
                          todoHeaderInfo.processing
                        }}</span>
                        <span class="card-list-item-unit">条</span>
                      </div>
                    </div>
                  </div>
                </a-col>
                <a-col :span="8">
                  <div class="card-list">
                    <div class="card-list-item" style="margin-left: 10px">
                      <div>我今日发起的待办共计</div>
                      <div class="card-list-item-desc">
                        <span class="card-list-item-value">{{
                          todoHeaderInfo.initiation
                        }}</span>
                        <span class="card-list-item-unit">条</span>
                      </div>
                    </div>
                  </div>
                </a-col>
                <a-col
                  :span="8"
                  v-for="(col, index) in todoHeaderInfo.categoricalStatistics"
                  :key="index"
                  @click="todoTypeClickHandler(col.cps)"
                >
                  <div class="card-list">
                    <div class="card-list-item">
                      <div>{{ col.label }}</div>
                      <div class="card-list-item-desc">
                        <span class="card-list-item-value">{{
                          col.value
                        }}</span>
                        <span class="card-list-item-unit">件</span>
                      </div>
                    </div>
                  </div>
                </a-col>
              </a-row>
            </a-card>
          </a-col>
          <a-col :span="24" v-else>
            <a-row :gutter="8" type="flex">
              <a-col v-if="firstColShow" :flex="13" style="width: 0">
                <a-card title="订单采购">
                  <template #extra>
                    <span
                      @click="onTabChange('personal', 'card1Key')"
                      :style="{
                        color: state.card1Key === 'personal' ? '#52acff' : ''
                      }"
                      >个人</span
                    >
                    <span v-if="state.isAdmin"> / </span>
                    <span
                      @click="onTabChange('department', 'card1Key')"
                      :style="{
                        color: state.card1Key === 'department' ? '#52acff' : ''
                      }"
                      v-if="state.isAdmin"
                      >部门</span
                    >
                  </template>

                  <a-row type="flex" :gutter="10">
                    <a-col
                      :span="8"
                      v-for="(item, index) in orderPurchaseInfo"
                      :key="index"
                    >
                      <div class="card-list">
                        <div class="card-list-item">
                          <div>{{ item.label }}</div>
                          <div class="card-list-item-desc">
                            <span
                              @click="orderPurchaseInfoClickHandler(item)"
                              class="card-list-item-value"
                            >
                              {{ item.value }}
                              <span>条</span>
                            </span>
                          </div>
                        </div>
                        <div class="card-list-line"></div>
                        <div class="card-list-item">
                          <div>
                            {{
                              item.label === '总数'
                                ? '关联SKC'
                                : item.label + 'SKC'
                            }}
                          </div>
                          <div class="card-list-item-desc">
                            <span
                              @click="orderPurchaseInfoClickHandler(item, true)"
                              class="card-list-item-value"
                            >
                              {{ item.skcValue }}
                              <span>件</span>
                            </span>
                          </div>
                        </div>
                      </div>
                    </a-col>
                  </a-row>
                </a-card>
              </a-col>
              <a-col v-if="secondColShow" :flex="4.5" style="width: 0">
                <a-card title="对账任务">
                  <template #extra>
                    <span
                      @click="onTabChange('personal', 'card2Key')"
                      :style="{
                        color: state.card2Key === 'personal' ? '#52acff' : ''
                      }"
                      >个人</span
                    >
                    <span v-if="state.isAdmin"> / </span>
                    <span
                      @click="onTabChange('department', 'card2Key')"
                      :style="{
                        color: state.card2Key === 'department' ? '#52acff' : ''
                      }"
                      v-if="state.isAdmin"
                      >部门</span
                    >
                  </template>
                  <a-row type="flex" :gutter="8">
                    <a-col
                      :span="24"
                      v-for="(item, index) in checkAccountInfo"
                      :key="index"
                    >
                      <div class="card-list">
                        <div class="card-list-item">
                          <div>{{ item.label }}</div>
                          <div class="card-list-item-desc">
                            <span
                              @click="checkAccountClickHandler(item)"
                              class="card-list-item-value"
                            >
                              {{ item.value }}
                              <span>条</span>
                            </span>
                          </div>
                        </div>
                        <div class="card-list-line"></div>
                        <div class="card-list-item">
                          <div>关联SKC</div>
                          <div class="card-list-item-desc">
                            <span
                              @click="checkAccountClickHandler(item, true)"
                              class="card-list-item-value"
                            >
                              {{ item.skcValue }}
                              <span>件</span>
                            </span>
                          </div>
                        </div>
                      </div>
                    </a-col>
                  </a-row>
                </a-card>
              </a-col>
              <a-col v-if="thirdColShow" :flex="3" style="width: 0">
                <a-card title="询期" class="inquiry-card">
                  <template #extra>
                    <span
                      @click="onTabChange('personal', 'card3Key')"
                      :style="{
                        color: state.card3Key === 'personal' ? '#52acff' : ''
                      }"
                      >个人</span
                    >
                    <span v-if="state.isAdmin"> / </span>
                    <span
                      @click="onTabChange('department', 'card3Key')"
                      :style="{
                        color: state.card3Key === 'department' ? '#52acff' : ''
                      }"
                      v-if="state.isAdmin"
                      >部门</span
                    >
                  </template>
                  <a-row type="flex" :gutter="8">
                    <a-col
                      :span="24"
                      v-for="(item, index) in inquiryInfo"
                      :key="index"
                    >
                      <div class="card-list">
                        <div class="card-list-item">
                          <div>{{ item.label }}</div>
                          <div class="card-list-item-desc">
                            <span
                              @click="inquiryClickHandler(item)"
                              class="card-list-item-value"
                            >
                              {{ item.value }}
                              <span>条</span>
                            </span>
                          </div>
                        </div>
                      </div>
                    </a-col>
                  </a-row>
                </a-card>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
      </a-spin>
    </a-form>
    <a-card
      class="select-card"
      :style="{
        height: state.selectDown ? '200px' : '31px'
      }"
    >
      <div @click="selectDirection">
        <span>展示项目选择</span>
        <span v-if="state.selectDown">
          <DownOutlined style="font-size: 10px" />
        </span>
        <span v-else>
          <UpOutlined style="font-size: 10px" />
        </span>
      </div>
      <Transition name="check-box">
        <div class="check-box-container" v-if="state.checkBoxShow">
          <a-checkbox-group
            style="
              display: flex;
              flex-direction: column;
              line-height: 30px;
              font-weight: normal;
            "
            v-model:value="state.checkedList"
            :options="state.plainOptions"
            @change="onChange"
          />
        </div>
      </Transition>
    </a-card>
    <a-tabs
      v-model:value="pageInfo.activeKey"
      size="large"
      class="mt10"
      @change="tabChangeHandler"
      v-if="false"
    >
      <a-tab-pane :key="1" tab="我的待办" />
      <a-tab-pane :key="2" tab="我已办结" />
      <a-tab-pane :key="3" tab="我的发起" />
    </a-tabs>
    <!-- 按钮 -->
    <!-- 催单，备注，导出，分配他人，流程查看 -->
    <a-space
      wrap="wrap"
      style="margin-top: 10px; justify-content: space-between; width: 100%"
    >
      <a-space wrap>
        <!-- 点击,发送催单 -->
        <a-button
          size="small"
          type="primary"
          @click="sendReminderBatch"
          v-if="false"
          :loading="state.reminderLoading"
          :disabled="state.reminderDisabledFlag"
        >
          催单
        </a-button>
        <a-button
          size="small"
          type="primary"
          v-if="false"
          @click="remarkHandler"
        >
          备注
        </a-button>
        <a-button size="small" type="primary" @click="completeTaskBatch">
          全部标为完成
        </a-button>
        <a-button
          size="small"
          type="primary"
          v-if="false"
          @click="todoTableExportExcel"
          :loading="state.exportLoading"
        >
          导出
        </a-button>
        <a-button
          size="small"
          @click="showSlaConfig"
          type="primary"
          v-if="false"
        >
          SLA配置
        </a-button>
      </a-space>
    </a-space>
    <!--    menu-name="todoData"-->
    <!--  我的待办table  -->
    <div>
      <remote-table
        ref="todoTable"
        v-if="state.todoRemoteTableShow"
        class="todo-table"
        v-model:value="state.todoTableData"
        menu-name="todoNotification"
        :show-selection="false"
        :has-export="false"
        :show-setting="false"
        :has-action="true"
        :has-refresh="false"
        :has-reset="false"
        :y="state.y"
        :sy="state.y"
        :row-key="(record, index) => index"
        :api-params="state.todoTableParams"
        interface-u-r-l="/todo/page"
        @change="selectTodoChange"
        :column-width="{
          task: 450
        }"
      >
        <template #action="{ record }">
          <a
            class="table-btns"
            @click="bomJumpToPage(record, record.addressRoute, 1)"
            v-if="!state.isAdmin && record.recordOperationType === 1"
            >去处理</a
          >
          <a
            class="table-btns"
            v-if="false && !record.reminderFlg"
            @click="sendReminder(record)"
            >催单
          </a>
          <a class="table-btns" v-if="false" @click="remarkHandler(record)"
            >备注</a
          >
          <a
            class="table-btns"
            @click="openAllocationModal(record)"
            v-if="record.recordOperationType === 1"
            >分配他人</a
          >
          <a-popover
            placement="left"
            :visiable="state.showProcessModal"
            trigger="click"
          >
            <template #content>
              <div class="process-timeline pt10">
                <a-spin :spinning="state.processModalSpinning">
                  <a-timeline>
                    <a-timeline-item
                      v-for="item in state.processArr"
                      :key="item.id"
                      color="green"
                    >
                      <p>{{ item.text }}</p>
                      <p>{{ item.operationTime }}</p>
                    </a-timeline-item>
                  </a-timeline>
                </a-spin>
              </div>
            </template>
            <a @click="openProcessModal(record)"> 流程查看 </a>
          </a-popover>
          <a-popconfirm
            title="是否确定将该条待办标为完成？"
            ok-text="确定"
            cancel-text="取消"
            @confirm="completeOneTask(record, record.addressRoute, 1)"
          >
            <a class="table-btns" v-if="record.recordOperationType === 1"
              >标为完成</a
            >
          </a-popconfirm>
        </template>
        <template #taskCR="{ record }">
          <a-space>
            <span>
              {{ record.task }}
              <a
                style="white-space: nowrap"
                @click="bomJumpToPage(record, record.taskAddress, 0)"
                >点击查看</a
              >
            </span>
          </a-space>
        </template>
        <template #cpCR="{ record }">
          <span>{{ transNullVal(record, 'cp') }}</span>
        </template>
        <template #productImgCR="{ record }">
          <view-img
            v-if="record.productImg"
            :src="record.productImg"
          ></view-img>
          <view-img v-else :src="$defaultImage"></view-img>
        </template>
        <template #businessTypeCR="{ record }">
          <span>{{ transBusinessType(record.businessType) }}</span>
        </template>
        <template #initiatorCR="{ record }">
          <span>{{ record.initiatorName }}</span>
        </template>
        <template #recordOperationTimeCR="{ record }">
          <span>{{ transNullVal(record, 'recordOperationTime') }}</span>
        </template>
        <template #recordOperationTypeCR="{ record }">
          <span>{{ transState(record.recordOperationType) }}</span>
        </template>
        <template #remarkCR="{ record }">
          <a v-if="record.remark" @click="remarkHistoryHandler(record)">{{
            transNullVal(record, 'remark')
          }}</a>
          <span v-else>-</span>
        </template>
      </remote-table>
    </div>

    <!-- 分配他人弹框 -->
    <allocationModal
      :show-allocation-modal="state.showAllocationModal"
      @closeModal="allocationModalClose"
      :record="state.nowTaskObj"
      @refresh="refreshTable"
    >
    </allocationModal>
    <slaConfigModal
      :show-sla-config-modal="state.showSlaConfigModal"
      :sla-type-options="state.slaTypeOptions"
      @closeModal="slaConfigModalClose"
    ></slaConfigModal>
    <!--  添加备注弹框  -->
    <remarkAddModal
      :showAddRemarkModal="state.showAddRemarkModal"
      :ids="state.remarkTableId"
      @closeModal="remarkModalClose"
      @refresh="refreshTable"
    ></remarkAddModal>
    <!-- 备注历史弹框 -->
    <remarkHistoryModal
      :show-remark-modal="state.showRemarkModal"
      :table-id="state.remarkHistoryId"
      @closeModal="remarkHistoryModalClose"
    >
      ></remarkHistoryModal
    >
  </div>
</template>
<script>
export default {
  name: 'TodoTableContent'
}
</script>
<script setup>
// import { UserOutlined, TeamOutlined } from '@ant-design/icons-vue'
import { useJumpToPage } from 'utils/useHook.js'
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { DownOutlined, UpOutlined } from '@ant-design/icons-vue'
import {
  todo_complete_post,
  todo_workflow_post,
  todo_complete_one_task,
  todo_complete_task_batch,
  todo_classification_count_normal,
  todo_classification_count_admin,
  todo_send_reminder_post,
  todo_is_admin,
  todo_sla_list_type,
  todo_count_purchase,
  todo_count_reconciliation,
  todo_count_inquiry,
  todo_count_purchase_department,
  todo_count_reconciliation_department,
  todo_count_inquiry_department,
  todo_export_post
} from 'server/modules/7537'
import { downloadFile } from 'utils/file.js'
import remarkAddModal from './module/remarkAddModal.vue'
import remarkHistoryModal from './module/remarkHistoryModal.vue'
import slaConfigModal from '@/components/todoTable/module/slaConfigModal'
import allocationModal from '@/components/todoTable/module/allocationModal'
import { postMessageToParent } from 'cupshe-utils'
const emit = defineEmits(['todoComplete', 'todoTableContentClick'])

// 采购员 (个人)
const personalUser = ref(null)
// 采购员 (部门)
const departmentUser = ref([])

const state = reactive({
  userId: null,
  y: window.innerHeight - 300,
  // 表格请求
  tableParams: {
    recordOperationType: [],
    tab: 1
  },
  // 表格请求参数枚举
  stateOptions: [
    // {
    //   optionName: '发起',
    //   value: 0
    // },
    {
      optionName: '处理中',
      value: 1
    },
    {
      optionName: '转移',
      value: 3
    },
    {
      optionName: '完成',
      value: 2
    }
  ],
  // 页面操作栏点击时，任务内容
  nowTaskObj: {},
  // 分配他人弹框
  showAllocationModal: false,
  // SLA配置弹窗
  showSlaConfigModal: false,
  // 新增SLA配置弹窗
  showCreateSlaConfigModal: false,
  // 添加备注弹框
  showAddRemarkModal: false,
  // 备注弹框
  showRemarkModal: false,
  allocationModalSpinning: false,
  // 可分配的对象 ，根据不同业务，导入不同的人
  allocationOptions: [],
  // 被选择分配的对象
  assignedID: null,
  loadingCreateSlaConfigBtn: false,
  // 控制分配弹窗-确定按钮Loading
  loadingConfirmAllocationBtn: false,
  // 流程查看弹窗
  showProcessModal: false,
  processArr: [],
  maxHeight: 300,
  processModalSpinning: false,
  slaTypeOptions: [],
  alarmDuration: null,
  timeoutDuratiojn: null,
  remarkHistoryId: null,
  remarkTableId: [],
  isAdmin: false,
  todoTableParams: {
    receiver: []
  },
  todoTableInterfaceUrl: '',
  plainOptions: [
    {
      label: '订单采购',
      value: 'orderPurchase'
    },
    {
      label: '对账任务',
      value: 'checkAccount'
    },
    {
      label: '询期',
      value: 'inquiry'
    }
  ],
  checkedList: [],
  indeterminate: true,
  checkAll: false,
  card1Key: 'personal',
  card2Key: 'personal',
  card3Key: 'personal',
  todoKey: 'personal',
  todoCardSpinning: false,
  selectOpen: false,
  reminderDisabledFlag: false,
  reminderLoading: false,
  exportLoading: false,
  selectRowKeys: [],
  todoTableData: [],
  todoRemoteTableShow: false,
  selectDown: false,
  checkBoxShow: false
})
const pageInfo = reactive({
  activeKey: 1,
  selectedRowKeys: []
})
const todoHeaderInfo = reactive({
  processing: 0,
  initiation: 0,
  categoricalStatistics: []
})
// 订单采购
const orderPurchaseInfo = ref([])
// 对账任务
const checkAccountInfo = ref([])
// 询期
const inquiryInfo = ref([])
const firstColShow = computed(() => {
  return (
    state.checkedList.length > 0 &&
    state.checkedList.find(item => item === 'orderPurchase')
  )
})
const secondColShow = computed(() => {
  return (
    state.checkedList.length > 0 &&
    state.checkedList.find(item => item === 'checkAccount')
  )
})
const thirdColShow = computed(() => {
  return (
    state.checkedList.length > 0 &&
    state.checkedList.find(item => item === 'inquiry')
  )
})
const todoTable = ref(null)
watch(
  () => state.todoTableData,
  val => {
    if (val.length > 0) {
      const flag = val.some(item => item.reminderFlg === null)
      if (flag) {
        state.reminderDisabledFlag = false
      } else {
        state.reminderDisabledFlag = true
      }
    }
  }
)
onMounted(() => {
  // 待办类型统计URL
  const checkedList = localStorage.getItem('todoCardCheckedList')
  if (checkedList) {
    state.checkedList = JSON.parse(checkedList)
  } else {
    state.checkedList = ['orderPurchase', 'checkAccount', 'inquiry']
  }
  state.todoCardSpinning = true
  if (state.checkedList.length > 0) {
    onChange(state.checkedList)
  }
  // 判断当前登陆人是否为admin
  todo_is_admin()
    .then(res => {
      personalUser.value = res.data ? res.data.userId : null
      if (res.data?.isAdmin === 1) {
        // 当前用户为admin
        state.isAdmin = true
        state.todoTableParams.receiver = res.data.staffList
        state.todoRemoteTableShow = true
        departmentUser.value = res.data.staffList
      } else {
        state.isAdmin = false
        state.todoRemoteTableShow = true
      }
      todo_classification_count_normal()
        .then(res => {
          todoHeaderInfo.processing = res.data.processing
            ? res.data.processing
            : 0
          todoHeaderInfo.initiation = res.data.initiation
            ? res.data.initiation
            : 0
          // 将res.data.categoricalStatistics 拷贝到todoHeaderInfo
          res.data.categoricalStatistics.forEach(item => {
            item.value = item.value ? item.value : 0
            todoHeaderInfo.categoricalStatistics.push(item)
          })
        })
        .finally(() => {
          state.todoCardSpinning = false
        })
    })
    .catch(() => {
      state.todoCardSpinning = false
    })
})
async function completeOneTask(elem) {
  state.todoCardSpinning = true
  const { success, retInfo, data } = await todo_complete_one_task(elem)
  if (success) {
    todoHeaderInfo.categoricalStatistics = []
    message.success(data)
    emit('todoComplete', elem)
    search()
    todo_classification_count_normal()
      .then(res => {
        todoHeaderInfo.processing = res.data.processing
        todoHeaderInfo.initiation = res.data.initiation
        // 将res.data.categoricalStatistics 拷贝到todoHeaderInfo
        res.data.categoricalStatistics.forEach(item => {
          item.value = item.value ? item.value : 0
          todoHeaderInfo.categoricalStatistics.push(item)
        })
      })
      .finally(() => {
        state.todoCardSpinning = false
      })
  } else {
    state.todoCardSpinning = false
    message.error(retInfo)
    console.log(retInfo)
  }
}
async function completeTaskBatch(val) {
  Modal.confirm({
    content: '是否确定将待办任务全部标为完成？',
    okText: '确定',
    cancelText: '取消',
    onOk: async function () {
      state.todoCardSpinning = true
      const { success, retInfo, data } = await todo_complete_task_batch(val)
      console.log(data)
      if (success) {
        message.success(data)
        search()
        state.todo_classification_count_url().then(res => {
          todoHeaderInfo.processing = res.data.processing
          todoHeaderInfo.initiation = res.data.initiation
          // 将res.data.categoricalStatistics 拷贝到todoHeaderInfo
          res.data.categoricalStatistics
            .forEach(item => {
              item.value = item.value ? item.value : 0
              todoHeaderInfo.categoricalStatistics.push(item)
            })
            .finally(() => {
              state.todoCardSpinning = false
            })
        })
      } else {
        state.todoCardSpinning = false
        message.error(retInfo)
      }
    }
  })
}
// 字典翻译
function transBusinessType(val) {
  let res = null
  if (val) {
    switch (val) {
      case 1:
        res = '调整工艺'
        break
      case 2:
        res = '款式核价'
        break
      case 10:
        res = '重新核价'
        break
      case 3:
      case 4:
      case 5:
      case 6:
      case 7:
      case 9:
        res = '样衣评审'
        break
    }
    return res
  } else {
    return '-'
  }
}
function transNullVal(elem, attribute) {
  if (elem[attribute]) {
    return elem[attribute]
  } else {
    return '-'
  }
}
function transState(val) {
  let res = null
  if (val) {
    switch (val) {
      case 0:
        res = '发起'
        break
      case 1:
        res = '处理中'
        break
      case 2:
        res = '完成'
        break
      case 3:
        res = '转移'
        break
    }
    return res
  } else {
    return '-'
  }
}
function search() {
  todoTable.value.refresh()
}
// eslint-disable-next-line no-unused-vars
function recordOperationTypeChange(val) {
  if (val?.length === 0) {
    search()
  }
}
// 去处理，根据数据内容跳转到指定页
// eslint-disable-next-line no-unused-vars
function toDispose(record) {
  console.log(record)
}
// 分配给他人弹窗
function openAllocationModal(record) {
  state.nowTaskObj = record
  state.showAllocationModal = true
}
// 查看某个任务的流程
async function openProcessModal(record) {
  state.processArr = []
  state.processModalSpinning = true
  const { success, retInfo, data } = await todo_workflow_post({
    workFlowCode: record.workFlowCode,
    businessType: record.businessType
  })
  if (success) {
    state.processArr = data
  } else {
    console.log(retInfo)
  }
  state.showProcessModal = true
  state.processModalSpinning = false
}
// 完成待办
async function todoComplete(params) {
  const { success, retInfo, data } = await todo_complete_post(params)
  if (success) {
    message.success(data)
  } else {
    console.log(retInfo)
  }
}
// BOM相关操作，跳转到指定地址
async function bomJumpToPage(record, url, index) {
  console.log(record)
  if (record.businessType === 9 && index === 1) {
    await todoComplete({
      cp: record.cp,
      businessDataCode: record.businessDataCode,
      businessModelCode: record.businessModelCode
    })
    todoTable.value.refresh()
  }
  if (!url) {
    message.error('跳转地址参数为空')
  }
  const pathStart = url.indexOf('/#/')

  const questionMarkIndex = url.indexOf('?')
  const params = new URLSearchParams(url.substring(questionMarkIndex + 1))

  const paramsObject = {}
  params.forEach(function (value, key) {
    paramsObject[key] = value
  })

  let pathStr = null
  let system = null
  if (url.indexOf('PLM2') !== -1) {
    system = 2
    pathStr = url.substring(pathStart + 3, questionMarkIndex)
  } else if (url.indexOf('PLM3') !== -1) {
    system = 3
    pathStr = url.substring(pathStart + 3, questionMarkIndex)
  }
  const option = {
    params: paramsObject,
    system: system
  }
  let title = null
  // 后续改为接口动态传值
  if (pathStr === 'bom') {
    title = 'BOM列表'
  } else {
    title = 'CP卡片'.concat(record.cp)
  }
  useJumpToPage(title, pathStr, option)
}
async function sendReminderBatch() {
  const selectedRow = state.todoTableData.filter((value, index) => {
    if (state.selectRowKeys.includes(index)) {
      return value
    }
  })
  if (selectedRow.length === 0) {
    message.error('请选择要催单的数据')
    return
  }
  state.reminderLoading = true
  const ids = selectedRow.map(({ id }) => id)
  const { success, retInfo, data } = await todo_send_reminder_post({
    ids
  })
  if (success) {
    todoTable.value.refresh()
    message.success(data)
  } else {
    console.log(retInfo)
  }
  state.reminderLoading = false
}
async function sendReminder(record) {
  const { success, retInfo, data } = await todo_send_reminder_post({
    ids: [record.id]
  })
  if (success) {
    todoTable.value.refresh()
    message.success(data)
  } else {
    console.log(retInfo)
  }
}
let showSlaConfig = function () {
  todo_sla_list_type().then(res => {
    state.slaTypeOptions = res.data
    // 惰性函数，防止多次调用请求
    showSlaConfig = function () {
      state.showSlaConfigModal = true
    }
    showSlaConfig()
  })
}
function remarkHistoryHandler(record) {
  state.showRemarkModal = true
  state.remarkHistoryId = record.id
}
function remarkHandler(record) {
  if (!record?.id && state.selectRowKeys.length === 0) {
    message.error('请选择一条记录')
    return
  }
  state.remarkTableId = record?.id ? [record.id] : []
  if (state.remarkTableId.length === 0) {
    const selectedRow = state.todoTableData.filter((value, index) => {
      if (state.selectRowKeys.includes(index)) {
        return value
      }
    })
    state.remarkTableId = selectedRow.map(({ id }) => id)
  }
  state.showAddRemarkModal = true
}
function todoTableExportExcel() {
  state.exportLoading = true
  todo_export_post({
    receiver: state.todoTableParams.receiver
  }).then(({ success, retInfo, data }) => {
    if (success) {
      downloadFile(data)
    } else {
      message.error(retInfo)
    }
    state.exportLoading = false
  })
}
function jumpToPage(title, path, params, system = 2) {
  const t = 't=' + Date.now()
  let queryStr = [t]
  Object.keys(params).forEach(key => {
    queryStr.push(`${key}=${params[key]}`)
  })
  if (queryStr.length) {
    queryStr = '?' + queryStr.join('&')
  }
  console.log(
    `${
      system === 3 ? process.env.VUE_APP_PLM3 : process.env.VUE_APP_PLM2
    }/#/${path}${queryStr}`
  )
  console.log(
    `${
      system === 3 ? process.env.VUE_APP_PLM3 : process.env.VUE_APP_PLM2
    }/#/${path}?t=${t}`
  )
  if (window.env_local) {
    window.open(
      `${
        system === 3 ? process.env.VUE_APP_PLM3 : process.env.VUE_APP_PLM2
      }/#/${path}${queryStr}`
    )
  } else {
    console.log('plm')
    postMessageToParent({
      type: 'breadcrumb',
      menuPath: `${
        system === 3 ? process.env.VUE_APP_PLM3 : process.env.VUE_APP_PLM2
      }/#/${path}${queryStr}`, // 详情从根目录开始的完整路由
      menuName: title, // 面包屑名称
      basePath: `${
        system === 3 ? process.env.VUE_APP_PLM3 : process.env.VUE_APP_PLM2
      }/#/${path}?t=${t}` // 详情从根目录开始基础路由
    })
  }
}
function todoTypeClickHandler(val) {
  val = [...new Set(val)]
  const queryInfo = {}
  if (val.length > 0) {
    queryInfo.cps = val
  }
  jumpToPage('产品开发管理', 'productDesign/waitDesignInfo', queryInfo, 2)
  // useJumpToPage('产品开发管理', 'productDesign/waitDesignInfo', {
  //   isDelete: true,
  //   system: 2,
  //   params: {
  //     ...queryInfo,
  //   },
  // })
  // setTimeout(() => {
  //   useJumpToPage('产品开发管理', 'productDesign/waitDesignInfo', {
  //     system: 2,
  //     params: {
  //       ...queryInfo
  //     }
  //   })
  // }, 800)
}
async function onChange(checkedList) {
  let url = null
  checkedList.forEach(async item => {
    let infoList = null
    if (item === 'orderPurchase') {
      url =
        state.card1Key === 'personal'
          ? todo_count_purchase
          : todo_count_purchase_department
      infoList = orderPurchaseInfo.value
    } else if (item === 'checkAccount') {
      url =
        state.card2Key === 'personal'
          ? todo_count_reconciliation
          : todo_count_reconciliation_department
      infoList = checkAccountInfo.value
    } else if (item === 'inquiry') {
      url =
        state.card3Key === 'personal'
          ? todo_count_inquiry
          : todo_count_inquiry_department
      infoList = inquiryInfo.value
    }
    const { success, retInfo, data } = await url()
    if (success) {
      data.forEach(item => {
        item.value = item.value ? item.value : 0
        item.skcValue = item.skcValue ? item.skcValue : 0
      })
      Object.assign(infoList, data)
    } else {
      message.error(retInfo)
    }
  })
  localStorage.setItem('todoCardCheckedList', JSON.stringify(checkedList))
  state.indeterminate =
    !!checkedList.length && checkedList.length < state.plainOptions.length
  state.checkAll = checkedList.length === state.plainOptions.length
}
async function onTabChange(key, type) {
  let url = null
  let info = null
  switch (type) {
    case 'card1Key':
      if (key === 'personal') {
        url = todo_count_purchase
      } else {
        url = todo_count_purchase_department
      }
      info = orderPurchaseInfo.value
      break
    case 'card2Key':
      if (key === 'personal') {
        url = todo_count_reconciliation
      } else {
        url = todo_count_reconciliation_department
      }
      info = checkAccountInfo.value
      break
    case 'card3Key':
      if (key === 'personal') {
        url = todo_count_inquiry
      } else {
        url = todo_count_inquiry_department
      }
      info = inquiryInfo.value
      break
  }
  const { success, retInfo, data } = await url()
  if (success) {
    if (data.length > 0) {
      data.forEach(item => {
        item.value = item.value ? item.value : 0
        item.skcValue = item.skcValue ? item.skcValue : 0
      })
      Object.assign(info, data)
    }
  } else {
    message.error(retInfo)
  }
  state[type] = key
}
function onTodoCardTabChange(key, type) {
  state[type] = key
  state.todoCardSpinning = true
  todoHeaderInfo.categoricalStatistics = []
  let url = todo_classification_count_admin
  if (key === 'personal') {
    url = todo_classification_count_normal
  } else {
    url = todo_classification_count_admin
  }
  url()
    .then(res => {
      todoHeaderInfo.processing = res.data.processing ? res.data.processing : 0
      todoHeaderInfo.initiation = res.data.initiation ? res.data.initiation : 0
      // 将res.data.categoricalStatistics 拷贝到todoHeaderInfo
      res.data.categoricalStatistics.forEach(item => {
        item.value = item.value ? item.value : 0
        todoHeaderInfo.categoricalStatistics.push(item)
      })
    })
    .finally(() => {
      state.todoCardSpinning = false
    })
}
function checkAccountClickHandler(val) {
  let menuName = '采购对账管理'
  switch (val.key) {
    case 'finish':
      menuName = `采购对账管理(已完成)`
      break
    case 'unFinish':
      menuName = `采购对账管理(未完成)`
      break
  }
  const queryInfo = {
    key: state.card2Key,
    dataKey: val.key
  }
  jumpToPage(menuName, 'PurchaseStatement', queryInfo, 3)
  // useJumpToPage(menuName, 'PurchaseStatement', {
  //   isDelete: true,
  //   system: 3,
  //   params: {
  //     ...queryInfo,
  //   },
  // })
  // setTimeout(() => {
  //   useJumpToPage(menuName, 'PurchaseStatement', {
  //     system: 3,
  //     params: {
  //       ...queryInfo,
  //     },
  //   })
  // }, 800)
}
function orderPurchaseInfoClickHandler(val) {
  let menuName = '采购订单-已审核'
  const queryInfo = {
    key: state.card1Key,
    dataKey: val.key
  }
  jumpToPage(
    menuName,
    'purchasingManagement/POmanagement/hasAudited',
    queryInfo,
    2
  )
  // useJumpToPage(menuName, 'purchasingManagement/POmanagement/hasAudited', {
  //   isDelete: true,
  //   system: 2,
  //   params: {
  //     ...queryInfo,
  //   },
  // })
  // setTimeout(() => {
  //   useJumpToPage(menuName, 'purchasingManagement/POmanagement/hasAudited', {
  //     system: 2,
  //     params: {
  //       ...queryInfo,
  //     },
  //   })
  // }, 800)
}

function inquiryClickHandler(val) {
  const queryInfo = {
    key: state.card3Key
  }
  // if (val.codeList && val.codeList.length > 0) {
  //   queryInfo.codeList = val.codeList
  // }
  const menuName = '询期计划:' + val.value
  jumpToPage(menuName, 'InquiryPeriodDetail', queryInfo, 3)
  // useJumpToPage(menuName, 'InquiryPeriodDetail', {
  //   isDelete: true,
  //   system: 3,
  //   params: {
  //     ...queryInfo,
  //   },
  // })
  // setTimeout(() => {
  //   useJumpToPage(menuName, 'InquiryPeriodDetail', {
  //     system: 3,
  //     params: {
  //       ...queryInfo,
  //     },
  //   })
  // }, 800)
}

function refreshTable() {
  todoTable.value.refresh()
}

function remarkModalClose() {
  state.remarkTableId = []
  state.showAddRemarkModal = false
}
function remarkHistoryModalClose() {
  state.showRemarkModal = false
}
function selectTodoChange(selectRowKeys) {
  state.selectRowKeys = selectRowKeys
}
function slaConfigModalClose() {
  state.showSlaConfigModal = false
}
function allocationModalClose() {
  state.showAllocationModal = false
}
function selectDirection() {
  state.selectDown = !state.selectDown
  if (state.selectDown) {
    state.checkBoxShow = true
  } else {
    state.checkBoxShow = false
  }
}
</script>

<style scoped lang="scss">
.table-btns {
  margin-right: 8px;
  white-space: nowrap;
}

.main-content {
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  height: 100%;

  p {
    margin-top: 0;
    margin-bottom: 1em;
  }

  .ant-space-align-center {
    margin-bottom: 0px !important;
  }
}

.process-timeline {
  max-height: 300px;
  min-height: 50px;
  overflow-y: auto;
}
::v-deep.ant-card {
  font-family: 'HarmonyOS Sans SC';
  height: calc(100% - 10px);
  border: 1px solid #e8e8e8;
  box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.15);
  margin-bottom: 10px;
  transition: all 0.5s ease;
  .ant-tabs {
    .ant-tabs-tab {
      padding: 0 0 5px 0;
    }
    .ant-tabs-nav-container {
      font-size: 14px !important;
    }
  }
  .ant-card-head {
    padding: 0 !important;
    border-bottom: 0px;
    .ant-card-head-title {
      font-weight: 500;
      min-height: auto !important;
      font-size: 18px;
      letter-spacing: 0px;
      color: rgba(29, 33, 41, 1);
      text-align: left;
      vertical-align: middle;
      margin: 15px 0 10px 16px;
      padding: 0px;
    }
    .ant-card-extra {
      font-size: 12px;
      font-weight: 500;
      letter-spacing: 0px;
      line-height: 29.35px;
      padding: 0px;
      margin: 16px 27px 12px 0;
      span:first-of-type,
      span:last-of-type {
        cursor: pointer;
      }
    }
  }
  .ant-card-body {
    margin: 0 16px 20px 17px;
    padding: 0px !important;
    .ant-row {
      row-gap: 12px !important;
      p {
        margin-bottom: 0;
      }
    }
    .card-list {
      display: flex;
      align-items: center;
      border-radius: 4px;
      background: rgba(247, 248, 250, 1);
      &-line {
        border-left: 1px solid #c0bcbc;
        margin: 0 2px;
        height: 25px;
        flex: 0.5;
        transform: translateX(50%);
      }
      &-item {
        font-weight: normal;
        display: flex;
        flex-direction: column;
        font-size: 12px;
        font-weight: 500;
        letter-spacing: 0px;
        line-height: 20px;
        color: rgba(78, 89, 105, 1);
        text-align: left;
        vertical-align: middle;
        flex: 1;
        &:first-of-type {
          margin: 16px 0 4px 12px;
        }
        &:last-of-type {
          margin: 16px 8px 4px 0;
        }
        &-desc {
          display: flex;
          align-items: center;
          justify-content: space-between;
          text-align: left;
          vertical-align: top;
          .card-list-item-value {
            width: 0;
            font-size: 20px;
            font-weight: 700;
            line-height: 37.35px;
            color: rgba(29, 33, 41, 1);
            flex-grow: 1;
          }
          span {
            font-size: 12px;
            font-weight: 500;
            letter-spacing: 0px;
            line-height: 26.68px;
            color: rgba(134, 144, 156, 1);
          }
          .ant-select {
            width: 100%;
          }
        }
        &-value {
          font-weight: bold;
          font-size: 20px;
          &:hover {
            cursor: pointer;
            color: #1890ff;
          }
        }
        &-unit {
          color: gray;
          margin-left: 5px;
        }
      }
    }
  }
}
:deep(.select-card) {
  z-index: 999;
  height: 46px;
  font-size: 14px;
  font-weight: 500;
  letter-spacing: 0px;
  line-height: 22px;
  color: rgba(29, 33, 41, 1);
  padding: 10px;
  text-align: left;
  vertical-align: top;
  position: absolute;
  top: 0;
  right: 80px;
  line-height: 30px;
  width: 200px;
  box-shadow: none;
  border-top: 0px;
  padding: 0 10px;
  .ant-card-body {
    display: flex;
    flex-direction: column;
    height: 100%;
    margin: 0;
    & > div:first-child {
      display: flex;
      justify-content: space-between;
      &:hover {
        cursor: pointer;
      }
    }
    .check-box-container {
      overflow: hidden;
      margin-top: 10px;
      padding: 0 10px !important;
      background: #f7f8fa;
      border-radius: 4px;
      flex-grow: 1;
      margin-bottom: 10px;
    }
  }
  .check-box-enter,
  .check-box-leave-to {
    opacity: 0;
  }

  .check-box-enter-to,
  .check-box-leave {
    opacity: 1;
  }
}
:deep(.inquiry-card) {
  .card-list-item {
    margin-left: 12px !important;
  }
}
::v-deep img {
  max-width: 100px !important;
  max-height: 100px !important;
  cursor: pointer;
  margin-right: 10px;
}
.check-box-enter-active,
.check-box-leave-active {
  transition: all 0.5s ease;
}
</style>
